package cn.com.digitalnet.ad.web.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.com.digitalnet.ad.security.UsernamePasswordCaptchaToken;
import cn.com.digitalnet.ad.service.UserService;

/***
 * 使用验证码的自定义filter，使实际使用的token是我们自定义的有验证码信息的token
 */
@Component
public class FormAuthenticationCaptchaFilter extends FormAuthenticationFilter {
	
	@Autowired private UserService accountService;

	public static final String DEFAULT_CAPTCHA_PARAM = "captcha";

	private String captchaParam = DEFAULT_CAPTCHA_PARAM;

	public String getCaptchaParam() {
		return captchaParam;
	}

	protected String getCaptcha(ServletRequest request) {
		return WebUtils.getCleanParam(request, getCaptchaParam());
	}

	@Override
	protected AuthenticationToken createToken(ServletRequest request,
			ServletResponse response) {
		String username = getUsername(request);
		String password = getPassword(request);
		String captcha = getCaptcha(request);
		boolean rememberMe = isRememberMe(request);

		String host = getHost(request);

		return new UsernamePasswordCaptchaToken(username,
				password.toCharArray(), rememberMe, host, captcha);
	}

	/**
	 * 登录成功后的回调函数
	 */
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token,
			Subject subject, ServletRequest request, ServletResponse response)
			throws Exception {
		//Long userId = ((ShiroUser) SecurityUtils.getSubject().getPrincipal()).id;
		//User user = accountService.getUser(userId);
		//Holder.rest_user.set(user);
		
		return super.onLoginSuccess(token, subject, request, response);
	}
}
